package com.woniuxy.pxxt.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.woniuxy.pxxt.common.enums.TrainEnrollFormStatus;
import com.woniuxy.pxxt.common.enums.UserTrainStatus;
import com.woniuxy.pxxt.common.result.Result;
import com.woniuxy.pxxt.common.result.ResultCodeEnum;
import com.woniuxy.pxxt.common.vo.train.TrainMsgVo;
import com.woniuxy.pxxt.dao.*;
import com.woniuxy.pxxt.dto.*;
import com.woniuxy.pxxt.dto.train.TrainMgsDtoSkc;
import com.woniuxy.pxxt.entity.Train;
import com.woniuxy.pxxt.common.vo.FindTrainUserScheduleVo;
import com.woniuxy.pxxt.dao.TrainDao;
import com.woniuxy.pxxt.entity.*;
import com.woniuxy.pxxt.entity.Train;
import com.woniuxy.pxxt.service.TestService;
import com.woniuxy.pxxt.service.TrainService;
import com.woniuxy.pxxt.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 培训处理
 * <P> Date: 2022/3/7:16:15
 * <P> Description:
 */
@Service
public class TrainServiceImpl implements TrainService {
    @Autowired(required = false)
    private TrainDao trainDao;

    @Autowired
    private UserScoreDao userScoreDao;

    @Autowired
    private TestService testService;

    @Autowired
    private ListSourceDao listSourceDao;

    @Autowired
    private CourseListDao courseListDao;


    @Autowired
    private UserDao userDao;

    @Autowired
    private CourseDao courseDao;

    @Override
    public Result findTrain(Integer currentPage, Integer pageSize, Train train) {
        PageHelper.startPage(currentPage, pageSize);
        List<FindTrainDto> trainList = trainDao.findTrain(train);
        PageInfo<FindTrainDto> findTrainDtoPageInfo = PageInfo.of(trainList);
        return Result.ok(findTrainDtoPageInfo);
    }


    @Override
    public Result addUserToTrain(Integer userId, Integer trainId) {
        //往用户培训表插入数据
        UserScore userScore = new UserScore();
        userScore.setUserId(userId);
        userScore.setTrainId(trainId);
        //TODO 表示参加 但是没有同意
        userScore.setIsSuccess(2);
        userScore.setUpdatePeople("skc");

        int i = userScoreDao.addUserScore(userScore);
        if (i > 0) {
            return Result.ok().message("报名成功");
        } else {
            return Result.fail().message("报名失败 稍后再试");
        }
    }

    @Override
    public Result findTrainUser(Integer trainId, Integer currentPage, Integer pageSize) {
        Train train = trainDao.findById(trainId);

        PageHelper.startPage(currentPage, pageSize);
        //通过培训id 返回对应的所有用户
        List<UserDtoSkc> users = trainDao.findTrainUser(trainId);
        if (users.size() < 1) {
            return Result.fail().message("当前培训没有人需要审核");
        }

        users.forEach(item -> {
            //打包返回类
            if (item != null && item.getEnrollForm() != null) {
                this.packUserDtoskc(item, train);
            }
        });
        PageInfo<UserDtoSkc> of = PageInfo.of(users);

        return Result.ok(of);
    }

    @Transactional
    @Override
    public Result delTrainById(Integer id) {
        trainDao.delTrainById(id);
        if (courseListDao.findResourceIsExist(id) > 0) {
            courseListDao.delResourceByTrain(id);
            listSourceDao.delResource(id);
        }
        return Result.ok();
    }


    @Override
    public Result findTrainUserSchedule(Integer currentPage, Integer pageSize,
                                        FindTrainUserScheduleVo findTrainUserScheduleVo) {

        //通过培训id 返回对应的所有用户的进度
        PageHelper.startPage(currentPage, pageSize);
        List<UserScheduleDto> userSchedule = trainDao.getUserSchedule(findTrainUserScheduleVo);
        PageInfo<UserScheduleDto> of = PageInfo.of(userSchedule);

        return Result.ok(of);
    }

    @Override
    public Result findTrainUserScore(Integer currentPage, Integer pageSize, FindTrainUserScheduleVo findTrainUserScheduleVo) {
        //通过培训id 返回对应的所有用户的进度
        PageHelper.startPage(currentPage, pageSize);
        //获得所有的培训进度 然后获取其成绩
        List<UserScheduleDto> userSchedule = trainDao.getUserScore(findTrainUserScheduleVo);

        userSchedule.forEach(item -> {
            //只要培训完成 才有考试
            Integer status = UserTrainStatus.getStatusInteger(item.getIsSuccess());
            if (status == 3 && item.getSchedule().intValue() == 100) {
                Result testScore = testService.findTestScore(item.getId(), findTrainUserScheduleVo.getTrainId());

                item.setScore((double) testScore.getData());
            }


        });

        PageInfo<UserScheduleDto> of = PageInfo.of(userSchedule);
        return Result.ok(of);
    }

    @Autowired
    private UserTrainDao userTrainDao;

    @Override
    @Transactional
    public Result setUserStatus(UserScoreDto userScoreDto, Integer status) {
        UserScore userScore = new UserScore();
        userScore.setIsSuccess(status);

        int num = userScoreDao.setUserStatus(userScoreDto, userScore);

        //查询出当前培训的id
        UserScore userScore1 =  userScoreDao.findTrainIdById(userScoreDto.getUserScoreId().get(0));
        //查询出当前培训的所有课程
        List<Integer> courseIds= courseDao.findCourseByTrainId(userScore1.getTrainId());

        //添加到用户课程进度表里面
        if(courseIds.size() >= 1){
            userTrainDao.add(userScore1.getUserId(),courseIds);
        }

        if (num > 0) {
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    @Override
    public Result findTrainById(Integer id) {
        FindViewTrainDtoSkc findViewTrainDtoSkc = trainDao.findViewTrainById(id);
        if(findViewTrainDtoSkc == null){
            return Result.fail().message("培训不存在");
        }
        return Result.ok(findViewTrainDtoSkc);
    }

    @Override
    public Result findTrainByIdEdit(Integer id) {
        TrainEditDto trainByIdEdit = trainDao.findTrainByIdEdit(id);
        return Result.ok(trainByIdEdit);
    }

    @Transactional
    @Override
    public Result updateTrain(String trainImgName, String trainImgUrl, Train train) {
        trainDao.updateTrain(train);
        if (listSourceDao.ResourceIsExist(train.getId()) > 0) {
            listSourceDao.updateResource(train.getId(), trainImgName, trainImgUrl);
        } else {
            ListSource listSource = new ListSource();
            listSource.setListUrl(trainImgUrl);
            listSource.setListName(trainImgName);
            listSource.setListFormat(1);
            listSourceDao.addTrainImg(listSource);
            PxxtCourseList pxxtCourseList = new PxxtCourseList();
            pxxtCourseList.setCourseId(train.getId());
            pxxtCourseList.setListId(listSource.getId());
            pxxtCourseList.setUrlStatus(1);
            courseListDao.addTrainList(pxxtCourseList);
        }
        return Result.ok();
    }

    @Override
    public Result findAllTrain(TrainMsgVo trainMsgVo) {
        List<TrainMgsDtoSkc> allTrainMsg = trainDao.findAllTrainMsg();
        trainMsgVo.setUserId(TokenUtil.getUser().getId());
        allTrainMsg.forEach(trainMgsDtoSkc -> {
            //找到当前用户相应的培训 设置状态
            UserScore userScore =
                    userDao.findTrainByTrainId(trainMgsDtoSkc.getId(), trainMsgVo.getUserId());
            trainMgsDtoSkc.setUrlImg("http://r7oxru06n.hn-bkt.clouddn.com/" + trainMgsDtoSkc.getUrlImg());

            //如果不为空 则设置状态
            if (userScore != null && userScore.getIsSuccess() != null) {
                trainMgsDtoSkc.setIsJoin(userScore.getIsSuccess());
            }
        });

        return Result.ok(allTrainMsg);
    }

    /**
     * TODO:打包返回UserDtoSkc类
     *
     * @param userDtoSkc 封装的用户 封装"报名形式(页面报名或手动添加)"
     * @param train      培训
     * @return
     */
    private void packUserDtoskc(UserDtoSkc userDtoSkc, Train train) {
        userDtoSkc.setEnrollForm(TrainEnrollFormStatus.getStatusNameByStatus(train.getEnrollForm()));
    }

    @Transactional
    @Override
    public Result createTrain(String trainImgName, String trainImgUrl, Train train) {
        Integer row = trainDao.createTrain(train);
        if (trainImgUrl != null && !trainImgUrl.equals("null")) {
            ListSource listSource = new ListSource();
            listSource.setListUrl(trainImgUrl);
            listSource.setListName(trainImgName);
            listSource.setListFormat(1);
            listSourceDao.addTrainImg(listSource);
            PxxtCourseList pxxtCourseList = new PxxtCourseList();
            pxxtCourseList.setCourseId(train.getId());
            pxxtCourseList.setListId(listSource.getId());
            pxxtCourseList.setUrlStatus(1);
            courseListDao.addTrainList(pxxtCourseList);
        }
        if (row > 0) {
            return Result.ok();
        }
        return Result.fail();
    }
}
